package com.wtb.listener;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;

import com.wtb.dao.OtDao;
import com.wtb.dao.QqDao;
import com.wtb.dao.RrDao;
import com.wtb.dao.impl.OtDaoImpl;
import com.wtb.dao.impl.QqDaoImpl;
import com.wtb.dao.impl.RrDaoImpl;
import com.wtb.domain.DataCache;
import com.wtb.domain.Other;
import com.wtb.pub.WtbException;
import com.wtb.qq.domain.QqOauth;
import com.wtb.rr.domain.RrOauth;
import com.wtb.utils.DateUtils;
import com.wtb.utils.JdbcUtils;
import com.wtb.utils.XmlUtils;

public class DateInitAndSaveListener implements ServletContextListener {
	private static final Log log = LogFactory.getLog(DateInitAndSaveListener.class);
	private ServletContext context;
	public void contextDestroyed(ServletContextEvent sce) {
	}
	public void contextInitialized(ServletContextEvent sce) {
		context = sce.getServletContext();
		int value = 0;
		//初始化数据库内数据
		QqDao qqDao = new QqDaoImpl();
		RrDao rrDao = new RrDaoImpl();
		OtDao otDao = new OtDaoImpl();
		List<QqOauth> qqList = null;
		List<RrOauth> rrList = null;
		Other other = new Other();
		other.setUni("count");
		try {
			qqList = qqDao.getAll();
			rrList = rrDao.getAll();
			other = otDao.get(other);
		} catch (Exception e) {
			log.error("数据初始化异常：", e);
			throw new WtbException("数据初始化异常",e);
		}finally{
			JdbcUtils.close();
		}
		if ( qqList.size() != rrList.size()) {
			log.info("数据库中数据错误！！");
			return;
		}
		if (qqList.size() != 0) {
			value = qqList.size();
			for(QqOauth qqOauth : qqList){
				DataCache.qqmap.put(qqOauth.getUni(), qqOauth);
				DataCache.qqlastTime.put(qqOauth.getUni(), DateUtils.systemTime());
				log.info("QQ数据初始化成功！！");
			}
			for (RrOauth rrOauth : rrList) {
				DataCache.rrmap.put(rrOauth.getUni(), rrOauth);
				DataCache.rrlastTime.put(rrOauth.getUni(), DateUtils.createTime());
				log.info("人人数据初始化成功！！");
			}
		}else {
			log.info("数据库中没有数据！！");
		}	
		//初始化用户数量
		DataCache.increment(value);
		DataCache.countIncrement(Integer.valueOf(other.getPara()));
	}
	/**
	 * 读入XML文件
	 * @param sc
	 * @param fileName
	 * @return
	 */
	@SuppressWarnings("unused")
	private Document getInto(ServletContext sc,String fileName){
		InputStream inputStream = null;
		Document document = null;
		try {
			inputStream = context
				.getResourceAsStream("data/"+fileName);
			document = XmlUtils.parse2Document(inputStream);
		} catch (Exception e) {
			log.error("读入数据信息失败：", e);
		}
		finally{
			try {
				inputStream.close();
			} catch (IOException e) {
				log.error("读入数据信息数据流关闭失败：", e);
			}
		}
		return document;
	}
	

}
